`timescale 1ns / 1ps
/*
 Copyright 2020 Sean Xiao, jxzsxsp@qq.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

module csr_mtval
(
    input sys_clk,

    input i_irq_src,
    input i_exp_src,
    input [ 31: 0 ] i_exe_pc,
    input [ 31: 0 ] i_ir,

    input [ 11: 0 ] i_csr_addr,
    input [ 31: 0 ] i_csr_val,
    input i_csr_wen,
    
    output [ 31: 0 ] o_mtval,

    input rst_n
);

/*
mtval  Machine Trap Value Register    RW
*/

wire sel_mtval = ( i_csr_addr == 12'h343 );

wire trap_mtval_ena = sel_mtval & i_exp_src;
wire [31:0] i_trap_mtval_val;

//0x343 MRW o_mtval Machine bad address.
wire wr_mtval = sel_mtval & i_csr_wen;

wire mtval_ena = ( wr_mtval & i_csr_wen ) | trap_mtval_ena;
wire [ 31: 0 ] mtval_r;
wire [ 31: 0 ] mtval_nxt;
assign mtval_nxt = trap_mtval_ena ? i_trap_mtval_val : i_csr_val;
yue_dfflr #( 32 ) mtval_dfflr ( mtval_ena, mtval_nxt, mtval_r, sys_clk, rst_n );

assign o_mtval = mtval_r;

endmodule
